from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import request
from flask import session

from info import constants
from info import db
from info.models import Category, News, User
from info.utlis.image_store import qiniu_image_store
from info.utlis.response_code import RET
from . import profile_bp
from flask import render_template
from info.utlis.common import login_user_data


@profile_bp.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)



@profile_bp.route('/other_info')
@login_user_data
def other_info():
    """查看其他用户信息"""
    user = g.user

    # 获取其他用户id
    user_id = request.args.get("id")
    if not user_id:
        abort(404)
    # 查询用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登陆用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据，　并返回
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "if_followed":is_followed

    }

    return render_template('news/other.html', data= data)


@profile_bp.route('/user_follow')
@login_user_data
def user_followed_list():
    """当前用户关注列表"""
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    user_list = []
    current_page = 1
    total_page = 1
    if user:
        try:

            # user.followed 如果直接使用，当前用户的偶像列表
            # user.followed 如果去查询 是一个查询对象
            paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
            # 获取当前页数据
            user_list = paginate.items
            # 获取当前页
            current_page = paginate.page
            # 获取总页数
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)

    user_dict_list = []

    for user in user_list if user_list else []:
        user_dict_list.append(user.to_dict())
    data = {"users": user_dict_list, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)




@profile_bp.route('/news_list')
@login_user_data
def news_list():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_news_list.html', data=data)


@profile_bp.route('/news_release', methods=['POST', 'GET'])
@login_user_data
def news_release():
    """展示新闻发布页面 发布新闻的后端逻辑"""
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
             current_app.logger.error(e)
        # 分类对象列表转成字典列表
        category_dict_list = []
        for category in categories if categories else []:
            category_dict_list.append(category.to_dict())
        # 注意点 ：需要移除最新分类
        category_dict_list.pop(0)
        return render_template("news/user_news_release.html", data={"categories":category_dict_list})

    # POST 请求发布新闻
    # 1.获取参数  从表单中直接获取
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest =request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    source = '个人发布'
    user = g.user
    # 2.参数校验
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 3.逻辑处理
    # 获取图片二进制数据
    image_data = index_image.read()
    try:
        image_name = qiniu_image_store(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云失败")
    # 创建新闻模型
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.content = content
    news.source = source
    news.user_id = user.id
    # 新闻处于审核中
    news.status = 1

    # 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存新闻对象到数据库异常")

    # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="新闻发布成功")







@profile_bp.route('/collection')
@login_user_data
def user_collection():
    """用户收藏列表展示"""
    # 1.参数获取
    p = request.args.get("p", 1)
    user = g.user
    # 2.参数校验
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p =1
    # lazy="dynamic"如果真正用到里面的值，就会给你返回一个列表数据，如果没有用到，就给你返回一个查询对象
    collections = []
    current_page = 1
    total_page = 1
    if user:
        try:
            paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
            # 获取分页数据
            collections = paginate.items
            # 获取当前页
            current_page = paginate.page
            # 获取总页数
            total_page = paginate.pages

        except Exception as e:
            current_app.logger.error(e)

        # 收藏列表
    collection_dict_li = []
    for news in collections if collections else []:
        collection_dict_li.append(news.to_basic_dict())

    data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_li}
    return render_template('news/user_collection.html', data=data)



# 密码修改接口
@profile_bp.route('/pass_info', methods=["GET", "POST"])
@login_user_data
def pass_info():
    if request.method =="GET":

        return render_template('news/user_pass_info.html')
    # POST 获取用户修改密码的参数
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 逻辑处理
    # 3.1 检查原来密码是否相等
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原始密码输入错误")
    # 3.2 密码正确 新密码赋值给password 属性（新密码判断给前端完成）
    user.password = new_password

    # 3.3 提交更新
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="修改密码成功")



# 用户头像接口
@profile_bp.route('/pic_info', methods=["POST", "GET"])
@login_user_data
def pic_info():
    """展示用户头像页面 修改用户头像接口"""
    if request.method == "GET":
        return render_template("news/user_pic_info.html")

    # POST获取用户上传的图片二进制数据上传到七牛云
    avatar_data = request.files.get("avatar").read()
    user = g.user

    # 校验参数
    if not avatar_data:
        return jsonify(errno=RET.NODATA, errmsg="图片数据不存在")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 逻辑处理
    try:
        # 调用封装好的方法
        image_name = qiniu_image_store(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云失败")

    user.avatar_url = image_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户url信息失败")

    # 4.组织响应对象
    full_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        "avatar_url":full_url
    }
    return jsonify(errno=RET.OK, errmsg="上传图片到七牛云成功", data=data)






@profile_bp.route("/base_info", methods=["POST", "GET"])
@login_user_data
def base_info():
    """获取用户基本资料，修改用户基本资料页面"""
    user = g.user
    if request.method =="GET":
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/user_base_info.html", data=data)

    # POST请求  修改用户基本资料#1.获取参数
    params_dict = request.json
    nick_name = params_dict.get("nick_name")
    signature = params_dict.get("signature")
    gender = params_dict.get("gender")

    #  2.1 非空判断
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 2.2 用户是否登录判断
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="action数据填写错误")

    #3.逻辑处理
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    # 更新session中的nick_name数据
    session["nick_name"] = nick_name

    # 将修改操作保存回数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改用户数据异常")

    #4.返回值处理
    return jsonify(errno=RET.OK, errmsg="修改用户数据成功")


# /user/info
@profile_bp.route('/info')
@login_user_data
def user_info():
    """返回个人中心页面"""
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None,
    }
    return render_template("news/user.html", data= data)